package cn.hongxin.sap.conn.task;

import cn.getech.poros.framework.common.api.RestResponse;
import cn.hongxin.basic.business.client.erp.BaErpFunctionClient;
import cn.hongxin.sap.conn.constants.ErpConstant;
import cn.hongxin.sap.conn.entity.ErpFunctionReturnVO;
import cn.hongxin.sap.conn.entity.ParamEntity;
import cn.hongxin.sap.conn.utils.HttpToolUtil;
import cn.hongxin.sap.conn.utils.SAPConnUtils;
import cn.hongxin.sap.conn.utils.SapCommHelp;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sap.conn.jco.*;
import com.sap.conn.jco.ext.DestinationDataProvider;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.HttpMethod;

import java.io.InputStream;
import java.io.SequenceInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MultiFromSAPBak {

    private static final Logger log = LoggerFactory.getLogger(MultiFromSAPBak.class);

    private String reg = "#[^#]*#";
    private Pattern pattern = Pattern.compile(reg);
    private SimpleDateFormat SF_DATETIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat SF_DATE = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat SF_TIME = new SimpleDateFormat("HH:mm:ss");
    private SimpleDateFormat SF_SAP_DATE = new SimpleDateFormat("yyyyMMdd");
    private SimpleDateFormat SF_SAP_TIME = new SimpleDateFormat("HHmmss");
    private SimpleDateFormat TIME_ZONE = new SimpleDateFormat("E MMM dd hh:mm:ss z yyyy", Locale.US);

    public ErpFunctionReturnVO callSapRfc(String id, Object paramJsonStr, SapCommHelp commHelp, ParamEntity paramEntity, BaErpFunctionClient baErpFunctionClient, RedisTemplate redisTemplate) {
        log.info("======================进入callSapRfc================");
        ErpFunctionReturnVO erpFunctionReturnVO = new ErpFunctionReturnVO();
        JCoDestination destination = null;

        //根据functionName得到相关一级信息
        Map<String, Object> functionMap = paramEntity.getFunctionMap();
        //String functionSql = "select * from ba_erp_function where id="+id;
        //Map<String, Object> functionMap = commHelp.queryForMap(functionSql);//查询出对应的函数信息，取到连接编号
        if (functionMap == null) {
            RuntimeException e = new RuntimeException(String.format("functionId:[%s] is not found in SQL!", id));
            log.error(e.getMessage());
            e.printStackTrace();
            erpFunctionReturnVO.setReturnErr(e.getMessage());
            return erpFunctionReturnVO;
        }
        erpFunctionReturnVO.setFunctionName(functionMap.get("functionname") + "");
        //根据连接编号获取连接信息
        String connid = String.valueOf(functionMap.get("connid"));
        //发送连接请求
        RestResponse connectResponse = baErpFunctionClient.queryConnectById(connid);
        Object connectData = connectResponse.getData();
        //Map<String, Object> connectMap = commHelp.queryForMap(queryConnect);//查出数据库中配置的客户端连接信息
//            if(connectData!=null){
        Map<String, Object> connectMap = (Map<String, Object>) connectData;
//                redisTemplate.opsForValue().set(ErpConstant.BA_ERP_CONNECTION+connid,connectMap, 24*60*60, TimeUnit.SECONDS);
//            }
//        }else{
//            connectMap = (Map<String, Object>)redisTemplate.opsForValue().get(ErpConstant.BA_ERP_CONNECTION+connid);
//        }

        if (connectMap == null) {
            RuntimeException e = new RuntimeException(String.format("Remote Connection:[%s] is not found in SQL!", connid));
            log.error(e.getMessage());
            e.printStackTrace();
            erpFunctionReturnVO.setReturnErr(e.getMessage());
            return erpFunctionReturnVO;
        }

        //restful类型SAP接口调用直接发起http请求
        String erpSysType = connectMap.get("erpsystype") + "";
        if ("restful".equals(erpSysType) && connectMap.get("hostaddr") != null) {
            String hostAddr = connectMap.get("hostaddr") + "";
            log.info("restful类型SAP接口调用；地址：" + hostAddr + ";函数id:" + id);
            String httpResult = HttpToolUtil.sendRequest(hostAddr, paramJsonStr, null, HttpMethod.POST, MediaType.APPLICATION_JSON);
            log.info("restful类型SAP接口调用返回结果：" + httpResult);
            erpFunctionReturnVO.setResult(httpResult);
            return erpFunctionReturnVO;
        }

        String needCommit = (String) functionMap.get("needcommit");
        String propertiesName = "ABAP_AS_" + connid;

        /*Properties connectProperties = new Properties();
        connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, connectMap.get("hostaddr")+"");//主机 例如：192.168.1.123
        connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR,  connectMap.get("sysnumber")+"");//系统号例如： "01"
        connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, connectMap.get("clientnumber")+"");//客户端例如： "300"
        connectProperties.setProperty(DestinationDataProvider.JCO_USER, connectMap.get("username")+""); //用户名 userName
        connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, connectMap.get("password")+"");//密码 password
        connectProperties.setProperty(DestinationDataProvider.JCO_LANG, connectMap.get("language")+"");//语种例如："EN"
        connectProperties.setProperty(DestinationDataProvider.JCO_MAX_GET_TIME, "1000");//超时
        //connectProperties.setProperty(DestinationDataProvider.JCO_SAPROUTER, "/H/113.105.10.236/S/3299/H/fxserv01");//SAProuter字符串
        String minActive = connectMap.get("minactive")+"";
        if(StringUtils.isNotBlank(minActive)){
            connectProperties.setProperty(DestinationDataProvider.JCO_POOL_CAPACITY, minActive);
        }
        String maxActive = connectMap.get("maxactive")+"";
        if(StringUtils.isNotBlank(maxActive)){
            connectProperties.setProperty(DestinationDataProvider.JCO_PEAK_LIMIT, maxActive);
         }

        CustomSAPDestinationDataProvider.MyDestinationDataProvider myProvider = CustomSAPDestinationDataProvider.MyDestinationDataProvider.getInstance();
        myProvider.addDestination(propertiesName, connectProperties);
        boolean isRegistered = Environment.isDestinationDataProviderRegistered();//是否已注册
        try {
            if(!isRegistered)
                Environment.registerDestinationDataProvider(myProvider);
            //myProvider.changeProperties(propertiesName,connectProperties);
        }catch(IllegalStateException providerException){//该连接池已注册
            //somebody else registered its implementation,
            //stop the execution
            log.error(providerException.getMessage());
            providerException.printStackTrace();
            erpFunctionReturnVO.setReturnErr(providerException.getMessage());
            return erpFunctionReturnVO;
        }*/

        try {
            Map<String, Object> paramMap = convertParam(paramJsonStr, paramEntity);
            //destination = JCoDestinationManager.getDestination(propertiesName);//连接池方式获取连接
            destination = SAPConnUtils.connect(propertiesName, connectMap);//配置文件解析获取连接
            //destination = SAPConnUtils.connect(commHelp, "AFW202006180001");
            if (destination == null) {
                RuntimeException e = new RuntimeException("Destination " + propertiesName + " is not available");
                log.error(e.getMessage());
                e.printStackTrace();
                erpFunctionReturnVO.setReturnErr(e.getMessage());
            } else {
                //JCoContext.begin(destination);//开启事务
                String functionstatus = (String) functionMap.get("functionstatus");
                System.out.println(functionMap.get("functionname"));
                JCoFunction function = destination.getRepository().getFunction((String) functionMap.get("functionname"));
                if (null == function) {
                    RuntimeException e = new RuntimeException("function " + propertiesName + " is not available");
                    log.error(e.getMessage());
                    e.printStackTrace();
                    erpFunctionReturnVO.setReturnErr(e.getMessage());
                }
                if (ErpConstant.FUNCTION_STATUS_ENABLE.equalsIgnoreCase(functionstatus)) {
                    log.info("======================进入sendSapRequest前;接口编号：" + id + "================");
                    erpFunctionReturnVO = sendSapRequest(destination, function, (String) functionMap.get("needcommit"), paramMap, paramEntity);

                    /*if(!ErpConstant.NEED_COMMIT_YES.equals(needCommit)){//不是过账接口
                        //查询接口对应映射表名，这里以单表返回为准，如之后查询接口存在返回多表且映射表也存在多表则需更改此处逻辑
                        String queryTableName = "select tablename,dataBaseName,isUseMappingTable from ba_erp_function_estruct where ba_erp_function_estruct_id="+id+" GROUP BY tablename,dataBaseName,isUseMappingTable";
                        *//*List<Map<String, Object>> tableNameList = commHelp.queryList(queryTableName);*//*
                        List<Map<String, Object>> tableNameList = null;
                        Object tableNameData = baErpFunctionClient.executeSelectSql(queryTableName).getData();
                        if(tableNameData!=null){
                            tableNameList = (List<Map<String, Object>>)tableNameData;//默认返回结果为List<Map<String, Object>>类型
                        }
                        //查询出来的映射表可能是多个，若其中有一个映射表存在数据则本次接口调用不执行数据同步
                        if(tableNameList!=null&&tableNameList.size()>0){
                            for(Map<String,Object> tableNameMap:tableNameList){
                                String checkTableName = (String)tableNameMap.get("tablename");
                                String dataBaseName = (String)tableNameMap.get("dataBaseName");
                                String isUseMappingTable = (String)tableNameMap.get("isUseMappingTable");//是否使用映射表插入数据
                                if(!"Y".equals(isUseMappingTable)){//若不使用映射表插入数据直接返回结果
                                    log.info("======================sendSapRequest执行完毕================,表："+checkTableName+"不执行映射表插入操作");
                                    return erpFunctionReturnVO;
                                }
                                if(StringUtils.isNotBlank(checkTableName)){//映射表不为null/空才检查
                                    String queryTableCount = "select count(*) from "+checkTableName;
                                    if(commHelp.queryTableCount(dataBaseName,queryTableCount)>0){//大于0代表接口对应映射表存在记录，后续操作结束，等待映射表清空数据后再执行
                                        *//*查询接口在执行映射表数据同步前先确认该映射表是否存在数据，若无数据则放行同步，有数据则请求结束
                     * 同时队列参数表对应的记录isexec值恢复成0，待映射表没有数据后才能执行映射表数据同步
                     *//*
                                        erpFunctionReturnVO.setType("N");
                                        log.info("======================sendSapRequest执行完毕================,表："+checkTableName+"存在数据，不执行数据同步操作");
                                        return erpFunctionReturnVO;//统计
                                    }
                                }
                            }
                        }

                    }*/

                    //saveReturnData(id, (String) functionMap.get("needCommit"), paramJsonStr, erpFunctionReturnVO, commHelp, paramEntity, baErpFunctionClient, redisTemplate);
                    log.info("======================进入sendSapRequest后================");
                    erpFunctionReturnVO.setFunctionName(functionMap.get("functionname") + "");
                } else {
                    RuntimeException e = new RuntimeException(String.format("SAP REMOTE FUNCTION[%s] IN TABLE[ELS_JK_FUN] STS[%s] DISABLE!", functionMap.get("functionName"), functionMap.get("functionStatus")));
                    log.warn(e.getMessage());
                    e.printStackTrace();
                    erpFunctionReturnVO.setReturnErr(e.getMessage());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            erpFunctionReturnVO.setReturnErr(e.getMessage());
        }
        /*finally {
            if(isRegistered)
            Environment.unregisterDestinationDataProvider(myProvider);//取消注册
        }*/
        return erpFunctionReturnVO;
    }

    private Map<String, Object> convertParam(Object paramJsonStr, ParamEntity paramEntity) throws Exception {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Object> jsonMap = (Map<String, Object>) paramJsonStr;

            /*String functionInputSql = "select * from ba_erp_function_import where ba_erp_function_import_id="+functionId;
            List<Map<String, Object>> functionInputList = commHelp.queryList(functionInputSql);*/
            List<Map<String, Object>> functionInputList = paramEntity.getFunctionImportList();
            List<Map<String, Object>> structParamMap = paramEntity.getFunctionIStructList();
            if (functionInputList != null && functionInputList.size() > 0) {
                for (Map<String, Object> convertInputMap : functionInputList) {
                    String paramName = (String) convertInputMap.get("paramname");
                    String paramType = (String) convertInputMap.get("paramtype");
                    String paramInputName = (String) convertInputMap.get("inputdataname");
                    String valueType = (String) convertInputMap.get("inputdatatype");
                    String dataFromType = (String) convertInputMap.get("inputdatafromtype");
                    String dataExpression = (String) convertInputMap.get("inputdataexpression");
                    String isSimpleStruct = String.valueOf(convertInputMap.get("isSimpleStruct"));

                    Map<String, Object> structMap;
                    List<Map<String, Object>> tablesParamList;
                    if (ErpConstant.PARAM_TYPE_SIMPLE.equalsIgnoreCase(paramType)) {
                        if (dataFromType != null && !"".equals(dataFromType)) {
                            if (ErpConstant.DATA_FROM_TYPE_VAR.equalsIgnoreCase(dataFromType)) {
                                Matcher m = pattern.matcher(dataExpression);
                                while (m.find()) {
                                    String mg = m.group();//#nodeName(.nodeName)#
                                    mg = mg.replaceAll("#", "");//去掉两端#标志
                                    String[] a = mg.split("\\.");
                                    if (a.length >= 1) {
                                        String replaceValue = (String) jsonMap.get(a[0]);
                                        if (replaceValue != null && !"".equals(replaceValue)) {
                                            dataExpression = dataExpression.replaceAll("#" + mg + "#", replaceValue);
                                        }
                                    }
                                }

                                if (dataExpression != null && !"".equals(dataExpression)) {
                                    paramMap.put(paramInputName, convertToSapType(valueType, dataExpression));
                                }
                            } else if (ErpConstant.DATA_FROM_TYPE_SQL.equalsIgnoreCase(dataFromType)) {
                                Matcher m = pattern.matcher(dataExpression);
                                while (m.find()) {
                                    String mg = m.group();//#nodeName(.nodeName)#
                                    mg = mg.replaceAll("#", "");//去掉两端#标志
                                    String[] a = mg.split("\\.");
                                    if (a.length >= 1) {
                                        String replaceValue = (String) jsonMap.get(a[0]);
                                        if (replaceValue != null && !"".equals(replaceValue)) {
                                            dataExpression = dataExpression.replaceAll("#" + mg + "#", replaceValue);
                                        }
                                    }
                                }

                            /*List<Map<String, Object>> erpRemoteFunctionList = erpRemoteFunctionMapper.getListMapBySql(dataExpression);
                            Object[] objArr = erpRemoteFunctionList.get(0).keySet().toArray();
                            Object value = erpRemoteFunctionList.get(0).get(objArr[0]);
                            if(value != null && !"".equals(String.valueOf(value))){
                                paramMap.put(paramName, value);
                            }*/
                            } else if (ErpConstant.DATA_FROM_TYPE_FORMULA.equalsIgnoreCase(dataFromType)) {
                                //TODO
                            } else {
                                //TODO
                            }
                        } else {
                            //如果是simple 类型 下面带了三级参数
                            if(StringUtils.equals("1",isSimpleStruct)){
                                if (structParamMap != null && structParamMap.size() > 0) {
                                    for (Map<String, Object> structVO : structParamMap) {
                                        String structParamName = (String) structVO.get("paramname");
                                        if (paramName.equalsIgnoreCase(structParamName)) {//二级参数名与三级参数名一致
                                            String paramField = (String) structVO.get("paramfieldname");
                                            String paramFieldType = (String) structVO.get("paramfieldtype");
                                            String inputDataName = (String) structVO.get("inputdataname");
                                        /*String  = structVO.getParamFieldName();
                                        String  = structVO.getParamFieldType();
                                        String  = structVO.getInputDataName();*/

                                            Object firstParamObj = jsonMap.get(paramName);
                                            if (firstParamObj == null || "".equals(firstParamObj.toString())) {//1级List入参为空，表示前台没有传对应的List参数，就只传单个或没传对应参数
                                                Object secondParamObj = jsonMap.get(paramField);
                                                if (secondParamObj != null && !"".equals(secondParamObj.toString())) {
                                                    if (paramMap.get(paramInputName) == null) {
                                                        tablesParamList = new ArrayList<Map<String, Object>>();
                                                        Map<String, Object> map = new HashMap<String, Object>();
                                                        map.put(inputDataName, convertToSapType(paramFieldType, jsonMap.get(paramField)));
                                                        tablesParamList.add(map);
                                                        paramMap.put(paramInputName, tablesParamList);
                                                    } else {
                                                        tablesParamList = (List<Map<String, Object>>) paramMap.get(paramInputName);
                                                        Map<String, Object> map = tablesParamList.get(0);//1级List入参为空，前台没有传对应的List参数，tablesParamList的size最大为1，直接取第一个
                                                        if (map != null && map.size() > 0) {
                                                            map.put(inputDataName, convertToSapType(paramFieldType, secondParamObj));
                                                        } else {
                                                            map = new HashMap<String, Object>();
                                                            map.put(inputDataName, convertToSapType(paramFieldType, secondParamObj));
                                                            tablesParamList.add(map);
                                                        }
                                                    }
                                                }
                                            } else {//1级List入参不为空，前台有传对应的List参数
                                                //JSONArray jsonArray = JSONArray.fromObject(firstParamObj);
                                                JavaType mtType = objectMapper.getTypeFactory().constructType(ArrayList.class, Map.class);

                                                List<Map<String, Object>> jsonList = null;
                                                String inputParamStr = JSONObject.toJSONString(firstParamObj);
                                                if (inputParamStr.indexOf("[") == -1 && inputParamStr.indexOf("]") == -1) {
                                                    inputParamStr = "[" + inputParamStr + "]";
                                                    jsonList = objectMapper.readValue(inputParamStr, mtType);
                                                } else {
                                                    jsonList = objectMapper.readValue(objectMapper.writeValueAsString(firstParamObj), mtType);
                                                }

                                                for (int i = 0; i < jsonList.size(); i++) {
                                                    Map<String, Object> recordMap = jsonList.get(i);
                                                    if (recordMap != null && recordMap.size() > 0) {
                                                        Object recordFieldValue = recordMap.get(paramField);
                                                        if (recordFieldValue != null && !"".equals(recordFieldValue)) {
                                                            if (paramMap.get(paramInputName) == null) {
                                                                tablesParamList = new ArrayList<Map<String, Object>>();
                                                                Map<String, Object> map = new HashMap<String, Object>();
                                                                map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                                tablesParamList.add(map);
                                                                paramMap.put(paramInputName, tablesParamList);
                                                            } else {
                                                                tablesParamList = (List<Map<String, Object>>) paramMap.get(paramInputName);
                                                                if (tablesParamList.size() > i) {
                                                                    Map<String, Object> map = tablesParamList.get(i);
                                                                    if (map != null && map.size() > 0) {
                                                                        map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                                    } else {
                                                                        map = new HashMap<String, Object>();
                                                                        map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                                        tablesParamList.add(map);
                                                                    }
                                                                } else {
                                                                    Map<String, Object> map = new HashMap<String, Object>();
                                                                    map.put(paramField, convertToSapType(paramFieldType, recordFieldValue));
                                                                    tablesParamList.add(map);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }else {
                                if (jsonMap.get(paramName) != null && !"".equals(jsonMap.get(paramName).toString())) {//有传参数才组装到参数集合paramMap中
                                    paramMap.put(paramInputName, convertToSapType(valueType, jsonMap.get(paramName)));
                                }
                            }
                        }
                    } else if (ErpConstant.PARAM_TYPE_STRUCT.equalsIgnoreCase(paramType)) {
                        if (dataFromType != null && !"".equals(dataFromType)) {
                            if (ErpConstant.DATA_FROM_TYPE_VAR.equalsIgnoreCase(dataFromType)) {//STRUCT类型只有一行数据，VAR单个变量值只对应单个值
                            } else if (ErpConstant.DATA_FROM_TYPE_SQL.equalsIgnoreCase(dataFromType)) {
                                Matcher m = pattern.matcher(dataExpression);
                                while (m.find()) {
                                    String mg = m.group();//#nodeName(.nodeName)#
                                    mg = mg.replaceAll("#", "");//去掉两端#标志
                                    String[] a = mg.split("\\.");
                                    if (a.length >= 1) {
                                        String replaceValue = (String) jsonMap.get(a[0]);
                                        if (replaceValue != null && !"".equals(replaceValue)) {
                                            dataExpression = dataExpression.replaceAll("#" + mg + "#", replaceValue);
                                        }
                                    }
                                }

                            /*List<Map<String, Object>> erpRemoteFunctionList = erpRemoteFunctionMapper.getListMapBySql(dataExpression);
                            Map<String, Object> temMap = erpRemoteFunctionList.get(0);//??????????Map<columnName,value>??????????????????SAP RFC????????????????????????paramMap?????????????????
                            if(temMap != null && temMap.size()> 0){

                                ElsErpFunctionStructVO conditionVO = new ElsErpFunctionStructVO();
                                conditionVO.setFunctionId(functionId);
                                conditionVO.setParamName(paramName);

                                List<ElsErpFunctionStructVO> structList = elsErpFunctionStructMapper.queryElsErpFunctionStructByCondition(conditionVO);

                                structMap = new HashMap<String, Object>();
                                for(ElsErpFunctionStructVO structVO : structList){
                                    String paramFieldName = structVO.getParamFieldName();
                                    String inputDataName = structVO.getInputDataName();
                                    structMap.put(paramFieldName, temMap.get(inputDataName));//??????????????????structField??
                                }
                                paramMap.put(paramName, structMap);
                            }*/
                            } else if (ErpConstant.DATA_FROM_TYPE_FORMULA.equalsIgnoreCase(dataFromType)) {
                                //TODO
                            } else {
                                //TODO
                            }
                        } else {
                            /*String queryStructParam = "select * from ba_erp_function_istruct where ba_erp_function_istruct_id=" + functionId + " and paramName='" + paramName + "'";
                            List<Map<String, Object>> structParamMap = commHelp.queryList(queryStructParam);*/
                            if (structParamMap != null && structParamMap.size() > 0) {
                                for (Map<String, Object> structVO : structParamMap) {
                                    String structParamName = (String) structVO.get("inputdataname");
                                    if (paramInputName.equalsIgnoreCase(structParamName)) {//二级参数名与三级参数名一致
                                        String paramFieldName = (String) structVO.get("paramfieldname");
                                        String paramFieldType = (String) structVO.get("paramdieldtype");
                                        String inputDataName = (String) structVO.get("inputdataname");

                                        if (paramInputName != null && !"".equals(paramInputName)) {//有一级JSON入参名
                                            if (jsonMap.get(paramName) != null && !"{}".equals(jsonMap.get(paramName).toString()) && !"".equals(jsonMap.get(paramName).toString())) {//有传参数才组装到参数集合paramMap中
                                                if (paramMap.get(paramInputName) == null) {
                                                    structMap = new HashMap<String, Object>();
                                                    structMap.put(inputDataName, convertToSapType(paramFieldType, ((Map<Object, Object>) jsonMap.get(paramInputName)).get(paramFieldName)));
                                                    paramMap.put(paramInputName, structMap);
                                                } else {
                                                    structMap = (Map<String, Object>) paramMap.get(paramInputName);
                                                    structMap.put(inputDataName, convertToSapType(paramFieldType, ((Map<Object, Object>) jsonMap.get(paramInputName)).get(paramFieldName)));
                                                }
                                            }
                                        } else {
                                            if (jsonMap.get(paramFieldName) != null
                                                    && !"{}".equals(jsonMap.get(paramFieldName).toString())
                                                    && !"".equals(jsonMap.get(paramFieldName).toString())) {//有传参数才组装到参数集合paramMap中
                                                if (paramMap.get(paramInputName) == null) {
                                                    structMap = new HashMap<String, Object>();
                                                    structMap.put(inputDataName, convertToSapType(paramFieldType, jsonMap.get(paramFieldName)));
                                                    paramMap.put(paramName, structMap);
                                                } else {
                                                    structMap = (Map<String, Object>) paramMap.get(paramInputName);
                                                    structMap.put(inputDataName, convertToSapType(paramFieldType, jsonMap.get(paramFieldName)));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else if (ErpConstant.PARAM_TYPE_TABLE.equalsIgnoreCase(paramType)) {
                        if (dataFromType != null && !"".equals(dataFromType)) {
                            if (ErpConstant.DATA_FROM_TYPE_VAR.equalsIgnoreCase(dataFromType)) {//STRUCT类型只有一行数据，VAR单个变量值只对应单个值
                            } else if (ErpConstant.DATA_FROM_TYPE_SQL.equalsIgnoreCase(dataFromType)) {
                                Matcher m = pattern.matcher(dataExpression);
                                while (m.find()) {
                                    String mg = m.group();//#nodeName(.nodeName)#
                                    mg = mg.replaceAll("#", "");//???????#???
                                    String[] a = mg.split("\\.");
                                    if (a.length >= 1) {
                                        String replaceValue = (String) jsonMap.get(a[0]);
                                        if (replaceValue != null && !"".equals(replaceValue)) {
                                            dataExpression = dataExpression.replaceAll("#" + mg + "#", replaceValue);
                                        }
                                    }
                                }

                            /*List<Map<String, Object>> erpRemoteFunctionList = erpRemoteFunctionMapper.getListMapBySql(dataExpression);

                            if(erpRemoteFunctionList != null && erpRemoteFunctionList.size()> 0){
                                List<Map<String, Object>> paramList = new ArrayList<Map<String, Object>>();

                                ElsErpFunctionStructVO conditionVO = new ElsErpFunctionStructVO();
                                conditionVO.setFunctionId(functionId);
                                conditionVO.setParamName(paramName);
                                List<ElsErpFunctionStructVO> structList = elsErpFunctionStructMapper
                                        .queryElsErpFunctionStructByCondition(conditionVO);

                                for(Map<String, Object> map : erpRemoteFunctionList){
                                    Map<String, Object> tempMap = new HashMap<String, Object>();
                                    for(ElsErpFunctionStructVO structVO : structList){
                                        String paramFieldName = structVO.getParamFieldName();
                                        String inputDataName = structVO.getInputDataName();
                                        tempMap.put(paramFieldName, map.get(inputDataName));//??????????????????structField??
                                    }
                                    paramList.add(tempMap);
                                }
                                paramMap.put(paramName, paramList);
                                //paramMap.put(paramName, resultList);
                            }*/
                            } else if (ErpConstant.DATA_FROM_TYPE_FORMULA.equalsIgnoreCase(dataFromType)) {
                                //TODO
                            } else {
                                //TODO
                            }
                        } else {
                            /*String queryStructParam = "select * from ba_erp_function_istruct where ba_erp_function_istruct_id=" + functionId + " and paramName='" + paramName + "'";
                            List<Map<String, Object>> structParamMap = commHelp.queryList(queryStructParam);*/
                            //table 类型
                            if (structParamMap != null && structParamMap.size() > 0) {
                                for (Map<String, Object> structVO : structParamMap) {
                                    String structParamName = (String) structVO.get("paramname");
                                    if (paramName.equalsIgnoreCase(structParamName)) {//二级参数名与三级参数名一致
                                        String paramField = (String) structVO.get("paramfieldname");
                                        String paramFieldType = (String) structVO.get("paramfieldtype");
                                        String inputDataName = (String) structVO.get("inputdataname");
                                        /*String  = structVO.getParamFieldName();
                                        String  = structVO.getParamFieldType();
                                        String  = structVO.getInputDataName();*/

                                        Object firstParamObj = jsonMap.get(paramName);
                                        if (firstParamObj == null || "".equals(firstParamObj.toString())) {//1级List入参为空，表示前台没有传对应的List参数，就只传单个或没传对应参数
                                            Object secondParamObj = jsonMap.get(paramField);
                                            if (secondParamObj != null && !"".equals(secondParamObj.toString())) {
                                                if (paramMap.get(paramInputName) == null) {
                                                    tablesParamList = new ArrayList<Map<String, Object>>();
                                                    Map<String, Object> map = new HashMap<String, Object>();
                                                    map.put(inputDataName, convertToSapType(paramFieldType, jsonMap.get(paramField)));
                                                    tablesParamList.add(map);
                                                    paramMap.put(paramInputName, tablesParamList);
                                                } else {
                                                    tablesParamList = (List<Map<String, Object>>) paramMap.get(paramInputName);
                                                    Map<String, Object> map = tablesParamList.get(0);//1级List入参为空，前台没有传对应的List参数，tablesParamList的size最大为1，直接取第一个
                                                    if (map != null && map.size() > 0) {
                                                        map.put(inputDataName, convertToSapType(paramFieldType, secondParamObj));
                                                    } else {
                                                        map = new HashMap<String, Object>();
                                                        map.put(inputDataName, convertToSapType(paramFieldType, secondParamObj));
                                                        tablesParamList.add(map);
                                                    }
                                                }
                                            }
                                        } else {//1级List入参不为空，前台有传对应的List参数
                                            //JSONArray jsonArray = JSONArray.fromObject(firstParamObj);
                                            JavaType mtType = objectMapper.getTypeFactory().constructType(ArrayList.class, Map.class);

                                            List<Map<String, Object>> jsonList = null;
                                            String inputParamStr = JSONObject.toJSONString(firstParamObj);
                                            if (inputParamStr.indexOf("[") == -1 && inputParamStr.indexOf("]") == -1) {
                                                inputParamStr = "[" + inputParamStr + "]";
                                                jsonList = objectMapper.readValue(inputParamStr, mtType);
                                            } else {
                                                jsonList = objectMapper.readValue(objectMapper.writeValueAsString(firstParamObj), mtType);
                                            }

                                            for (int i = 0; i < jsonList.size(); i++) {
                                                Map<String, Object> recordMap = jsonList.get(i);
                                                if (recordMap != null && recordMap.size() > 0) {
                                                    Object recordFieldValue = recordMap.get(paramField);
                                                    if (recordFieldValue != null && !"".equals(recordFieldValue)) {
                                                        if (paramMap.get(paramInputName) == null) {
                                                            tablesParamList = new ArrayList<Map<String, Object>>();
                                                            Map<String, Object> map = new HashMap<String, Object>();
                                                            map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                            tablesParamList.add(map);
                                                            paramMap.put(paramInputName, tablesParamList);
                                                        } else {
                                                            tablesParamList = (List<Map<String, Object>>) paramMap.get(paramInputName);
                                                            if (tablesParamList.size() > i) {
                                                                Map<String, Object> map = tablesParamList.get(i);
                                                                if (map != null && map.size() > 0) {
                                                                    map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                                } else {
                                                                    map = new HashMap<String, Object>();
                                                                    map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                                    tablesParamList.add(map);
                                                                }
                                                            } else {
                                                                Map<String, Object> map = new HashMap<String, Object>();
                                                                map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                                tablesParamList.add(map);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else if (ErpConstant.PARAM_TYPE_RANGE.equalsIgnoreCase(paramType)) {//range类型
                        if (dataFromType != null && !"".equals(dataFromType)) {
                            if (ErpConstant.DATA_FROM_TYPE_VAR.equalsIgnoreCase(dataFromType)) {//STRUCT类型只有一行数据，VAR单个变量值只对应单个值
                            } else if (ErpConstant.DATA_FROM_TYPE_SQL.equalsIgnoreCase(dataFromType)) {
                                Matcher m = pattern.matcher(dataExpression);
                                while (m.find()) {
                                    String mg = m.group();//#nodeName(.nodeName)#
                                    mg = mg.replaceAll("#", "");//替换两端#标识
                                    String[] a = mg.split("\\.");
                                    if (a.length >= 1) {
                                        String replaceValue = (String) jsonMap.get(a[0]);
                                        if (replaceValue != null && !"".equals(replaceValue)) {
                                            dataExpression = dataExpression.replaceAll("#" + mg + "#", replaceValue);
                                        }
                                    }
                                }

                            /*List<Map<String, Object>> erpRemoteFunctionList = erpRemoteFunctionMapper.getListMapBySql(dataExpression);

                            if(erpRemoteFunctionList != null && erpRemoteFunctionList.size()> 0){
                                List<Map<String, Object>> paramList = new ArrayList<Map<String, Object>>();

                                ElsErpFunctionStructVO conditionVO = new ElsErpFunctionStructVO();
                                conditionVO.setFunctionId(functionId);
                                conditionVO.setParamName(paramName);
                                List<ElsErpFunctionStructVO> structList = elsErpFunctionStructMapper
                                        .queryElsErpFunctionStructByCondition(conditionVO);

                                for(Map<String, Object> map : erpRemoteFunctionList){
                                    Map<String, Object> tempMap = new HashMap<String, Object>();
                                    for(ElsErpFunctionStructVO structVO : structList){
                                        String paramFieldName = structVO.getParamFieldName();
                                        String inputDataName = structVO.getInputDataName();
                                        tempMap.put(paramFieldName, map.get(inputDataName));//??????????????????structField??
                                    }
                                    paramList.add(tempMap);
                                }
                                paramMap.put(paramName, paramList);
                                //paramMap.put(paramName, resultList);
                            }*/
                            } else if (ErpConstant.DATA_FROM_TYPE_FORMULA.equalsIgnoreCase(dataFromType)) {
                                //TODO
                            } else {
                                //TODO
                            }
                        } else {
                            /*String queryStructParam = "select * from ba_erp_function_istruct where ba_erp_function_istruct_id=" + functionId + " and paramName='" + paramName + "'";
                            List<Map<String, Object>> structParamMap = commHelp.queryList(queryStructParam);*/
                            if (structParamMap != null && structParamMap.size() > 0) {
                                for (Map<String, Object> structVO : structParamMap) {
                                    String structParamName = (String) structVO.get("paramname");
                                    if (paramName.equalsIgnoreCase(structParamName)) {//二级参数名与三级参数名一致
                                        String paramField = (String) structVO.get("paramfieldname");
                                        String paramFieldType = (String) structVO.get("paramfieldtype");
                                        String inputDataName = (String) structVO.get("inputdataname");
                                        /*String  = structVO.getParamFieldName();
                                        String  = structVO.getParamFieldType();
                                        String  = structVO.getInputDataName();*/

                                        Object firstParamObj = jsonMap.get(paramName);
                                        if (firstParamObj == null || "".equals(firstParamObj.toString())) {//1级List入参为空，表示前台没有传对应的List参数，就只传单个或没传对应参数
                                            Object secondParamObj = jsonMap.get(paramField);
                                            if (secondParamObj != null && !"".equals(secondParamObj.toString())) {
                                                if (paramMap.get(paramInputName) == null) {
                                                    tablesParamList = new ArrayList<Map<String, Object>>();
                                                    Map<String, Object> map = new HashMap<String, Object>();
                                                    map.put(inputDataName, convertToSapType(paramFieldType, jsonMap.get(paramField)));
                                                    tablesParamList.add(map);
                                                    paramMap.put(paramInputName, tablesParamList);
                                                } else {
                                                    tablesParamList = (List<Map<String, Object>>) paramMap.get(paramInputName);
                                                    Map<String, Object> map = tablesParamList.get(0);//1级List入参为空，前台没有传对应的List参数，tablesParamList的size最大为1，直接取第一个
                                                    if (map != null && map.size() > 0) {
                                                        map.put(inputDataName, convertToSapType(paramFieldType, secondParamObj));
                                                    } else {
                                                        map = new HashMap<String, Object>();
                                                        map.put(inputDataName, convertToSapType(paramFieldType, secondParamObj));
                                                        tablesParamList.add(map);
                                                    }
                                                }
                                            }
                                        } else {//1级List入参不为空，前台有传对应的List参数
                                            //JSONArray jsonArray = JSONArray.fromObject(firstParamObj);
                                            JavaType mtType = objectMapper.getTypeFactory().constructType(ArrayList.class, Map.class);
                                            String jsonStr = "[" + JSONObject.toJSONString(firstParamObj) + "]";
                                            List<Map<String, Object>> jsonList = objectMapper.readValue(jsonStr, mtType);
                                            for (int i = 0; i < jsonList.size(); i++) {
                                                Map<String, Object> recordMap = jsonList.get(i);
                                                if (recordMap != null && recordMap.size() > 0) {
                                                    Object recordFieldValue = recordMap.get(paramField);
                                                    if (recordFieldValue != null && !"".equals(recordFieldValue)) {
                                                        if (paramMap.get(paramInputName) == null) {
                                                            tablesParamList = new ArrayList<Map<String, Object>>();
                                                            Map<String, Object> map = new HashMap<String, Object>();
                                                            map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                            tablesParamList.add(map);
                                                            paramMap.put(paramInputName, tablesParamList);
                                                        } else {
                                                            tablesParamList = (List<Map<String, Object>>) paramMap.get(paramInputName);
                                                            if (tablesParamList.size() > i) {
                                                                Map<String, Object> map = tablesParamList.get(i);
                                                                if (map != null && map.size() > 0) {
                                                                    map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                                } else {
                                                                    map = new HashMap<String, Object>();
                                                                    map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                                    tablesParamList.add(map);
                                                                }
                                                            } else {
                                                                Map<String, Object> map = new HashMap<String, Object>();
                                                                map.put(inputDataName, convertToSapType(paramFieldType, recordFieldValue));
                                                                tablesParamList.add(map);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        //TODO
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw e;
        }
        return paramMap;
    }

    /**
     * 根据数据表相关配置信息，接收并解析SAP返回数据，返回同样根据配置信息指定的格式进行返回
     *
     * @param destination
     * @param function
     * @param needCommit
     * @param paramMap
     * @param
     * @return
     */
    private ErpFunctionReturnVO sendSapRequest(JCoDestination destination, JCoFunction function, String needCommit,
                                               Map<String, Object> paramMap, ParamEntity paramEntity) throws Exception {

        log.info("SapRemoteServiceExecute.sendSapRequest start");
        ErpFunctionReturnVO returnVO = new ErpFunctionReturnVO();
        Map<String, Object> simpleMap = new HashMap<String, Object>();
        Map<String, Map<String, Object>> structMap = new HashMap<String, Map<String, Object>>();
        Map<String, List<Map<String, Object>>> tablesMap = new HashMap<String, List<Map<String, Object>>>();

        try {

            //查询入参一层表数据
            /*String functionInputSql = "select * from ba_erp_function_import where ba_erp_function_import_id="+functionId+"";
            List<Map<String, Object>> functionInputList = commHelp.queryList(functionInputSql);*/
            //数据库中拉取得字段信息
            List<Map<String, Object>> functionInputList = paramEntity.getFunctionImportList();
            List<Map<String, Object>> functionIStructList = paramEntity.getFunctionIStructList();

            for (Map<String, Object> inputMap : functionInputList) {
                String paramName = (String) inputMap.get("inputdataname");
                String paramType = (String) inputMap.get("paramtype");
                String paramDefaultValue = (String) inputMap.get("paramvalue");
                String isChange = (String) inputMap.get("ischange");
                String isSimpleStruct = String.valueOf(inputMap.get("isSimpleStruct"));
                String inputParam= (String) inputMap.get("paramname");

                //查询入参二层表数据
                /*String functionInputStructSql = "select * from ba_erp_function_istruct where ba_erp_function_istruct_id="+functionId+" and paramName='"+paramName+"'";
                List<Map<String, Object>> functionIStructList = commHelp.queryList(functionInputStructSql);*/
                //if(functionIStructList == null || functionIStructList.size() == 0){//只有单值结构,无STRUCT结构或Tables结构参数
                //设置普通字符参数
                if (ErpConstant.PARAM_TYPE_SIMPLE.equalsIgnoreCase(paramType)) {
                    Object paramObject = paramMap.get(paramName);
                    if (paramObject != null && !"".equals(paramObject.toString().trim())) {
                        if ("1".equals(isChange)) {
                            function.getChangingParameterList().setValue(paramName, paramObject);
                        } else {
                            //为simple 类型的字段设置值
                            if (StringUtils.equals("1", isSimpleStruct)) {
                                for (Map<String, Object> iStructMap : functionIStructList) {
                                    String iParamNameChild = (String) iStructMap.get("paramname");
                                    if (paramName.equalsIgnoreCase(iParamNameChild)) {//二级参数名与三级参数名匹配
                                        String paramFieldName = (String) iStructMap.get("inputdataname");
                                        String paramFieldDefaultValue = (String) iStructMap.get("paramfieldvalue");

                                        List<Map<String, Object>> structParamMaps =(List<Map<String, Object>>) paramMap.get(paramName);
                                        for (Map<String, Object> structParamMap : structParamMaps) {
                                            if (structParamMap != null && structParamMap.size() > 0) {////TABLS结构有入参数据传进来
                                                JCoStructure jCoStructure = null;
                                                if ("1".equals(isChange)) {//参数类型为更改参数
                                                    jCoStructure = function.getChangingParameterList().getStructure(paramName);
                                                } else {
                                                    jCoStructure = function.getImportParameterList().getStructure(paramName);
                                                }
                                                Object paramValue = structParamMap.get(paramFieldName);
                                                if (paramValue != null && !"".equals(paramValue.toString().trim())) {
                                                    jCoStructure.setValue(paramFieldName, structParamMap.get(paramFieldName));
                                                } else {//有STRUCT结构的参数，但该字段参数未传入的
                                                    if (paramFieldDefaultValue != null && !"".equals(paramFieldDefaultValue)) {//有默认值的，传入默认值
                                                        jCoStructure.setValue(paramFieldName, paramFieldDefaultValue);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                function.getImportParameterList().setValue(paramName, paramObject);
                            }
                        }

                    } else {
                        if (paramDefaultValue != null && !"".equals(paramDefaultValue)) {
                            function.getImportParameterList().setValue(paramName, paramDefaultValue);
                        }
                    }
                } else {
                    for (Map<String, Object> iStructMap : functionIStructList) {
                        String iParamNameChild = (String) iStructMap.get("paramname");
                        if (inputParam.equalsIgnoreCase(iParamNameChild)) {//二级参数名与三级参数名匹配
                            String paramFieldName = (String) iStructMap.get("inputdataname");
                            String paramFieldDefaultValue = (String) iStructMap.get("paramfieldvalue");
                            if (ErpConstant.PARAM_TYPE_STRUCT.equalsIgnoreCase(paramType)) {
                                Map<String, Object> structParamMap = (Map<String, Object>) paramMap.get(paramName);
                                if (structParamMap != null && structParamMap.size() > 0) {//STRUCT结构有入参数据传进来
                                    JCoStructure jcoStructure = null;
                                    if ("1".equals(isChange)) {//参数类型为更改参数
                                        jcoStructure = function.getChangingParameterList().getStructure(paramName);
                                    } else {
                                        jcoStructure = function.getTableParameterList().getStructure(paramName);
                                    }
                                    Object paramValue = structParamMap.get(paramFieldName);
                                    if (paramValue != null && !"".equals(paramValue.toString().trim())) {
                                        jcoStructure.setValue(paramFieldName, structParamMap.get(paramFieldName));
                                    } else {//有STRUCT结构的参数，但该字段参数未传入的
                                        if (paramFieldDefaultValue != null && !"".equals(paramFieldDefaultValue)) {//有默认值的，传入默认值
                                            jcoStructure.setValue(paramFieldName, paramFieldDefaultValue);
                                        }
                                    }
                                }
                            } else if (ErpConstant.PARAM_TYPE_TABLE.equalsIgnoreCase(paramType)) {
                                List<Map<String, Object>> tablesParamList = (List<Map<String, Object>>) paramMap.get(paramName);
                                if (tablesParamList != null && tablesParamList.size() > 0) {////TABLS结构有入参数据传进来
                                    JCoTable jcoTable = null;
                                    if ("1".equals(isChange)) {//参数类型为更改参数
                                        jcoTable = function.getChangingParameterList().getTable(paramName);
                                    } else {
                                        jcoTable = function.getTableParameterList().getTable(paramName);
                                    }
                                    for (int i = 0; i < tablesParamList.size(); i++) {
                                        int tableRowsNum = jcoTable.getNumRows();
                                        if (tableRowsNum >= i + 1) {//表数据行大于等于当前参数行
                                            jcoTable.setRow(i);//移动到指定行
                                            Object paramValue = tablesParamList.get(i).get(paramFieldName);
                                            if (paramValue != null && !"".equals(paramValue.toString().trim())) {
                                                jcoTable.setValue(paramFieldName, paramValue);
                                            } else {//有TABLES结构的参数，但List参数中该字段参数未传入的
                                                if (paramFieldDefaultValue != null && !"".equals(paramFieldDefaultValue)) {//有默认值的，传入默认值
                                                    jcoTable.setValue(paramFieldName, paramFieldDefaultValue);
                                                }
                                            }
                                        } else {//表数据行小于当前参数行
                                            jcoTable.appendRows(i + 1 - tableRowsNum);
                                            jcoTable.setRow(i);//移动到指定行
                                            Object paramValue = tablesParamList.get(i).get(paramFieldName);
                                            if (paramValue != null && !"".equals(paramValue.toString().trim())) {
                                                jcoTable.setValue(paramFieldName, paramValue);
                                            } else {//有TABLES结构的参数，但List参数中该字段参数未传入的
                                                if (paramFieldDefaultValue != null && !"".equals(paramFieldDefaultValue)) {//有默认值的，传入默认值
                                                    jcoTable.setValue(paramFieldName, paramFieldDefaultValue);
                                                }
                                            }
                                        }
                                    }
                                }
                            } else if (ErpConstant.PARAM_TYPE_RANGE.equalsIgnoreCase(paramType)) {
                                List<Map<String, Object>> tablesParamList = (List<Map<String, Object>>) paramMap.get(paramName);
                                if (tablesParamList != null && tablesParamList.size() > 0) {////RANGE结构有入参数据传进来
                                    JCoTable jcoTable = null;
                                    if ("1".equals(isChange)) {//参数类型为更改参数
                                        jcoTable = function.getChangingParameterList().getTable(paramName);
                                    } else {
                                        jcoTable = function.getTableParameterList().getTable(paramName);
                                    }

                                    for (int i = 0; i < tablesParamList.size(); i++) {
                                        int tableRowsNum = jcoTable.getNumRows();
                                        if (tableRowsNum >= i + 1) {//表数据行大于等于当前参数行
                                            jcoTable.setRow(i);//移动到指定行
                                            Object paramValue = tablesParamList.get(i).get(paramFieldName);
                                            if (paramValue != null && !"".equals(paramValue.toString().trim())) {
                                                jcoTable.setValue(paramFieldName, paramValue);
                                            } else {//有RANGE结构的参数，但List参数中该字段参数未传入的
                                                if (paramFieldDefaultValue != null && !"".equals(paramFieldDefaultValue)) {//有默认值的，传入默认值
                                                    jcoTable.setValue(paramFieldName, paramFieldDefaultValue);
                                                }
                                            }
                                        } else {//表数据行小于当前参数行
                                            jcoTable.appendRows(i + 1 - tableRowsNum);
                                            jcoTable.setRow(i);//移动到指定行
                                            Object paramValue = tablesParamList.get(i).get(paramFieldName);
                                            if (paramValue != null && !"".equals(paramValue.toString().trim())) {
                                                jcoTable.setValue(paramFieldName, paramValue);
                                            } else {//有RANGE结构的参数，但List参数中该字段参数未传入的
                                                if (paramFieldDefaultValue != null && !"".equals(paramFieldDefaultValue)) {//有默认值的，传入默认值
                                                    jcoTable.setValue(paramFieldName, paramFieldDefaultValue);
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {//其他类型
                                //TODO
                            }
                        }
                    }
                }
            }
            //int k= 1/0;
            function.execute(destination);//执行sap查询

            //获取输出参数一层表
            /*String functionExportSql = "select * from ba_erp_function_export where ba_erp_function_export_id="+functionId;
            List<Map<String, Object>> functionExportList = commHelp.queryList(functionExportSql);*/

            List<Map<String, Object>> functionExportList = paramEntity.getFunctionExportList();
            List<Map<String, Object>> functionEStructList = paramEntity.getFunctionEStructList();

            if (functionExportList != null) {
                for (Map<String, Object> exportMap : functionExportList) {
                    String paramName = (String) exportMap.get("paramname");
                    String paramType = (String) exportMap.get("paramtype");
                    String isChange = (String) exportMap.get("ischange");
                    //String functionEStructSql = "select * from erp_function_estruct where pid='"+functionId+"' and paramfieldname='"+paramName+"'";
                    //获取输出参数二层表
                    /*String functionEStructSql = "select * from ba_erp_function_estruct where ba_erp_function_estruct_id="+functionId+" and paramName='"+paramName+"'";
                    List<Map<String, Object>> functionEStructList = commHelp.queryList(functionEStructSql);*/
                    //if(functionEStructList == null || functionEStructList.size() == 0){//只有单值结构,无STRUCT结构或Tables结构参数
                    if (ErpConstant.PARAM_TYPE_SIMPLE.equalsIgnoreCase(paramType)) {
                        try {
                            Object paramValue = null;
                            if ("1".equals(isChange)) {//参数类型为更改参数
                                paramValue = function.getChangingParameterList().getValue(paramName);
                            } else {
                                paramValue = function.getExportParameterList().getValue(paramName);
                            }
                            simpleMap.put(paramName, paramValue);
                        } catch (JCoRuntimeException e) {
                            System.out.println(e.getMessage());
                            log.info(paramEntity.getFunctionMap().get("functionname") + " " + e.getMessage());
                            simpleMap.put(paramName, "");
                        }

                        //}
                    } else {
                        for (Map<String, Object> structVO : functionEStructList) {
                            String eParamNameChild = (String) structVO.get("paramname");
                            if (paramName.equals(eParamNameChild)) {
                                String paramFieldType = (String) structVO.get("paramfieldtype");
                                /*
                                 *如果导出表中配置的字段类型为exportMainKey则代表该字段实际SAP接口并无返回，
                                 * 仅作为映射表主键存在，用来关联更新对应映射表数据
                                 */
                                if (ErpConstant.EXPORT_MAIN_KEY.equals(paramFieldType))
                                    continue;
                                String paramFieldName = (String) structVO.get("paramfieldname");
                                String inputDataName = (String) structVO.get("inputdataname");
                                String operateMothodName = (String) structVO.get("operatemothodname");
                                String operateParam = (String) structVO.get("operateparam");
                                String exportDataType = (String) structVO.get("exportdatatype");
                                String keyName = "";
                                log.info("SapRemoteServiceExecute.sendSapRequest  paramName: " + "paramFieldName: " + paramFieldName + " ,inputDataName:" + inputDataName);
                                if (StringUtils.isNotBlank(inputDataName)) {
                                    keyName = inputDataName;
                                } else {
                                    keyName = paramFieldName;
                                }
                                if (ErpConstant.PARAM_TYPE_STRUCT.equalsIgnoreCase(paramType)) {
                                    log.info("SapRemoteServiceExecute.sendSapRequest 进入STRUCT");
                                    Map<String, Object> stMap = structMap.get(paramName);
                                    Object val = null;
                                    if ("1".equals(isChange)) {//参数类型为更改参数
                                        //structure = function.getChangingParameterList().getStructure(paramName);
                                        val = function.getChangingParameterList().getStructure(paramName).getValue(paramFieldName);
                                    } else {
                                        val = function.getExportParameterList().getStructure(paramName).getValue(paramFieldName);
                                    }
                                    //Object val = function.getExportParameterList().getStructure(paramName).getValue(paramFieldName);

                                    //log.error("SapRemoteServiceExecute.sendSapRequest " + keyName + "    table222   " + val);
                                    Object paramFieldValue = null;
                                    if ("1".equals(isChange)) {//参数类型为更改参数
                                        //structure = function.getChangingParameterList().getStructure(paramName);
                                        paramFieldValue = function.getChangingParameterList().getStructure(paramName).getValue(paramFieldName);
                                    } else {
                                        paramFieldValue = function.getExportParameterList().getStructure(paramName).getValue(paramFieldName);
                                    }
                                    if (stMap != null) {
                                        stMap.put(keyName, paramFieldValue);
                                        //stMap.put(keyName, function.getExportParameterList().getStructure(paramName).getValue(paramFieldName));
//								stMap.put(paramFieldName, function.getExportParameterList().getStructure(paramName).getValue(paramFieldName));
                                        stMap.put(keyName, val);
                                    } else {
                                        stMap = new HashMap<String, Object>();
                                        stMap.put(keyName, paramFieldValue);
                                        //stMap.put(keyName, function.getExportParameterList().getStructure(paramName).getValue(paramFieldName));
//								stMap.put(paramFieldName,function.getExportParameterList().getStructure(paramName).getValue(paramFieldName));
                                        stMap.put(keyName, val);
                                        structMap.put(paramName, stMap);
                                    }
                                } else if (ErpConstant.PARAM_TYPE_TABLE.equalsIgnoreCase(paramType)) {
                                    JCoTable returnTable = null;
                                    if ("1".equals(isChange)) {//参数类型为更改参数
                                        returnTable = function.getChangingParameterList().getTable(paramName);
                                    } else {
                                        returnTable = function.getTableParameterList().getTable(paramName);
                                    }
                                    log.info("SapRemoteServiceExecute.sendSapRequest 进入TABLES");
                                    if (ErpConstant.DATA_TYPE_BINARY_PART.equalsIgnoreCase(paramFieldType)) {//一个对象拆分后形成的多个BINARY,最终需多个合并成一个才能还原原对象
                                        log.info("SapRemoteServiceExecute.sendSapRequest 进入TABLES  BINARY_PART");
                                        Vector<InputStream> vector = new Vector<InputStream>();
                                        for (int i = 0; i < returnTable.getNumRows(); i++) {
                                            returnTable.setRow(i);
                                            InputStream contentPartIn = returnTable.getBinaryStream(paramFieldName);
                                            vector.addElement(contentPartIn);
                                        }
                                        SequenceInputStream sin = new SequenceInputStream(vector.elements());
                                        byte[] b = new byte[1024];
                                        int len = 0;
                                        int arrSize = 0;
                                        List<byte[]> arrList = new ArrayList<byte[]>();
                                        while ((len = sin.read(b)) != -1) {
                                            arrSize += len;
                                            byte[] t = new byte[len];
                                            System.arraycopy(b, 0, t, 0, len);
                                            arrList.add(t);
                                        }
                                        byte[] buf = new byte[arrSize];
                                        int pos = 0;
                                        for (byte[] bArr : arrList) {
                                            System.arraycopy(bArr, 0, buf, pos, bArr.length);
                                            pos += bArr.length;
                                        }

                                        sin.close();

                                        List<Map<String, Object>> tableList = new ArrayList<Map<String, Object>>();
                                        Map<String, Object> tempMap = new HashMap<String, Object>();
//								tempMap.put(paramFieldName, buf);
                                        tempMap.put(keyName, buf);
                                        tableList.add(tempMap);
                                        tablesMap.put(paramName, tableList);
                                    } else {
                                        log.info("SapRemoteServiceExecute.sendSapRequest 进入TABLES 拼参");
                                        List<Map<String, Object>> tableList = tablesMap.get(paramName);
                                        for (int i = 0; i < returnTable.getNumRows(); i++) {
                                            returnTable.setRow(i);
                                            Object val = returnTable.getString(paramFieldName);
                                            if (StringUtils.isNotBlank(operateMothodName)) {
                                                //val=systemUtil.executeOperate(operateMothodName, operateParam, val);
                                            } else {
                                                //val=IntefaceUtil.convertDateType(val,exportDataType);
                                            }
                                            //log.error(keyName + "    table111   " + val);
                                            if (tableList != null) {
                                                Map<String, Object> tempMap;
                                                if (tableList.size() > i) {
                                                    tempMap = tableList.get(i);
                                                    if (tempMap != null) {
//												tempMap.put(paramFieldName, returnTable.getString(paramFieldName));
                                                        tempMap.put(keyName, val);
                                                    } else {
                                                        tempMap = new HashMap<String, Object>();
//												tempMap.put(paramFieldName, returnTable.getString(paramFieldName));
//												tempMap.put(keyName, returnTable.getString(paramFieldName));
                                                        tempMap.put(keyName, val);
                                                        tableList.add(tempMap);
                                                    }
                                                } else {
                                                    tempMap = new HashMap<String, Object>();
//											tempMap.put(paramFieldName, returnTable.getString(paramFieldName));
//											tempMap.put(keyName, returnTable.getString(paramFieldName));
                                                    tempMap.put(keyName, val);
                                                    tableList.add(tempMap);
                                                }
                                            } else {
                                                tableList = new ArrayList<Map<String, Object>>();
                                                Map<String, Object> tempMap = new HashMap<String, Object>();
//										tempMap.put(paramFieldName, returnTable.getString(paramFieldName));
//										tempMap.put(keyName, returnTable.getString(paramFieldName));
                                                tempMap.put(keyName, val);
                                                tableList.add(tempMap);
                                                tablesMap.put(paramName, tableList);
                                            }
                                        }
                                    }
                                } else if (ErpConstant.PARAM_TYPE_TB_TABLE.equalsIgnoreCase(paramType)) {
                                    JCoTable returnTable = null;
                                    if ("1".equals(isChange)) {//参数类型为更改参数
                                        returnTable = function.getChangingParameterList().getTable(paramName);
                                    } else {
                                        returnTable = function.getTableParameterList().getTable(paramName);
                                    }
                                    System.out.println("获取到的数据总长度为:" + returnTable.getNumRows());
                                    log.info("SapRemoteServiceExecute.sendSapRequest 进入TB_TABLES");
                                    if (ErpConstant.DATA_TYPE_BINARY_PART.equalsIgnoreCase(paramFieldType)) {//一个对象拆分后形成的多个BINARY,最终需多个合并成一个才能还原原对象
                                        log.info("SapRemoteServiceExecute.sendSapRequest 进入TB_TABLES  BINARY_PART");
                                        Vector<InputStream> vector = new Vector<InputStream>();
                                        for (int i = 0; i < returnTable.getNumRows(); i++) {
                                            returnTable.setRow(i);
                                            InputStream contentPartIn = returnTable.getBinaryStream(paramFieldName);
                                            vector.addElement(contentPartIn);
                                        }
                                        SequenceInputStream sin = new SequenceInputStream(vector.elements());
                                        byte[] b = new byte[1024];
                                        int len = 0;
                                        int arrSize = 0;
                                        List<byte[]> arrList = new ArrayList<byte[]>();
                                        while ((len = sin.read(b)) != -1) {
                                            arrSize += len;
                                            byte[] t = new byte[len];
                                            System.arraycopy(b, 0, t, 0, len);
                                            arrList.add(t);
                                        }
                                        byte[] buf = new byte[arrSize];
                                        int pos = 0;
                                        for (byte[] bArr : arrList) {
                                            System.arraycopy(bArr, 0, buf, pos, bArr.length);
                                            pos += bArr.length;
                                        }

                                        sin.close();

                                        List<Map<String, Object>> tableList = new ArrayList<Map<String, Object>>();
                                        Map<String, Object> tempMap = new HashMap<String, Object>();
//								tempMap.put(paramFieldName, buf);
                                        tempMap.put(keyName, buf);
                                        tableList.add(tempMap);
                                        tablesMap.put(paramName, tableList);
                                    } else {
                                        log.info("SapRemoteServiceExecute.sendSapRequest 进入TABLES");
                                        List<Map<String, Object>> tableList = tablesMap.get(paramName);
                                        for (int i = 0; i < returnTable.getNumRows(); i++) {
                                            returnTable.setRow(i);
                                            Object val = returnTable.getString(paramFieldName);
                                            if (StringUtils.isNotBlank(operateMothodName)) {
                                                //val=systemUtil.executeOperate(operateMothodName, operateParam, val);
                                            } else {
                                                //val=IntefaceUtil.convertDateType(val,exportDataType);
                                            }
                                            //log.error(keyName+"    table111   "+val);
                                            if (tableList != null) {
                                                Map<String, Object> tempMap;
                                                if (tableList.size() > i) {
                                                    tempMap = tableList.get(i);
                                                    if (tempMap != null) {
//												tempMap.put(paramFieldName, returnTable.getString(paramFieldName));
                                                        tempMap.put(keyName, val);
                                                    } else {
                                                        tempMap = new HashMap<String, Object>();
//												tempMap.put(paramFieldName, returnTable.getString(paramFieldName));
//												tempMap.put(keyName, returnTable.getString(paramFieldName));
                                                        tempMap.put(keyName, val);
                                                        tableList.add(tempMap);
                                                    }
                                                } else {
                                                    tempMap = new HashMap<String, Object>();
//											tempMap.put(paramFieldName, returnTable.getString(paramFieldName));
//											tempMap.put(keyName, returnTable.getString(paramFieldName));
                                                    tempMap.put(keyName, val);
                                                    tableList.add(tempMap);
                                                }
                                            } else {
                                                tableList = new ArrayList<Map<String, Object>>();
                                                Map<String, Object> tempMap = new HashMap<String, Object>();
//										tempMap.put(paramFieldName, returnTable.getString(paramFieldName));
//										tempMap.put(keyName, returnTable.getString(paramFieldName));
                                                tempMap.put(keyName, val);
                                                tableList.add(tempMap);
                                                tablesMap.put(paramName, tableList);
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }

            if (ErpConstant.NEED_COMMIT_YES.equals(needCommit)) {//需要调用SAP标准提交方法
                List<Map<String, Object>> returnList = tablesMap.get("RETURN");
                boolean hasError = false;
                if (returnList != null) {
                    for (Map<String, Object> map : returnList) {
                        String resultType = (String) map.get("TYPE");
                        if (resultType != null) {
                            if (ErpConstant.RETURN_TYPE_ERROR.equals(resultType)
                                    || ErpConstant.RETURN_TYPE_SUSPEND.equals(resultType)) {
                                hasError = true;
                                break;
                            }
                        }
                    }
                }
                if (!hasError) {//所有数据都正确则执行提交操作
                    JCoFunction commitFunction = destination.getRepository().getFunction("BAPI_TRANSACTION_COMMIT");
                    commitFunction.getImportParameterList().setValue("WAIT", "X");
                    commitFunction.execute(destination);//执行提交

                    //获取提交方法执行结果
                    if (commitFunction.getExportParameterList() != null) {
                        JCoStructure returnStruct = commitFunction.getExportParameterList().getStructure("RETURN");
                        if (returnStruct != null) {
                            Map<String, Object> resultStructMap = new HashMap<String, Object>();
                            resultStructMap.put("TYPE", returnStruct.getValue("TYPE"));
                            resultStructMap.put("NUMBER", returnStruct.getValue("NUMBER"));
                            resultStructMap.put("MESSAGE", returnStruct.getValue("MESSAGE"));
                            resultStructMap.put("LOG_NO", returnStruct.getValue("LOG_NO"));
                            resultStructMap.put("LOG_MSG_NO", returnStruct.getValue("LOG_MSG_NO"));
                            resultStructMap.put("MESSAGE_V1", returnStruct.getValue("MESSAGE_V1"));
                            resultStructMap.put("MESSAGE_V2", returnStruct.getValue("MESSAGE_V2"));
                            resultStructMap.put("MESSAGE_V3", returnStruct.getValue("MESSAGE_V3"));
                            resultStructMap.put("MESSAGE_V4", returnStruct.getValue("MESSAGE_V4"));

                            structMap.put("COMMIT_RETURN", resultStructMap);
                        }
                    }
                }
            }

            returnVO.setSimpleMap(simpleMap);
            returnVO.setStructMap(structMap);
            returnVO.setTablesMap(tablesMap);
            log.info("====SAP输出结果==simpleMap===" + simpleMap.size());
            log.info("====SAP输出结果==structMap===" + structMap.size());
            log.info("====SAP输出结果==tablesMap===" + tablesMap.size());
            log.info("SapRemoteServiceExecute.sendSapRequest end");

        } catch (
                Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw e;
        }

        return returnVO;
    }

    //将查询出来的数据保存到对应的映射表
    private void saveReturnData(String functionId, String needCommit, String paramMap, ErpFunctionReturnVO returnVO,
                                SapCommHelp commHelp, ParamEntity paramEntity, BaErpFunctionClient baErpFunctionClient, RedisTemplate redisTemplate) throws Exception {
        try {

            List<Map<String, Object>> functionExportList = paramEntity.getFunctionExportList();
            List<Map<String, Object>> functionEStructList = paramEntity.getFunctionEStructList();

            /*String functionExportSql = "select * from ba_erp_function_export where ba_erp_function_export_id="+functionId;
            List<Map<String, Object>> functionExportList = commHelp.queryList(functionExportSql);*/
            //errorMap用于存储保存操作失败的记录
            StringBuffer errorSb = new StringBuffer();
            String paramName = "";
            //判断是否有配置导出结构
            if (functionExportList != null && functionExportList.size() > 0) {
                //循还导出表
                for (Map<String, Object> exportMap : functionExportList) {
                    Map<String, Object> exportMainMap = new HashMap<String, Object>();
                    paramName = exportMap.get("paramname") + "";//对应SAP接口返回表名
                    String paramType = exportMap.get("paramtype") + "";

                    /*String functionEStructSql = "select * from ba_erp_function_estruct where ba_erp_function_estruct_id="+functionId+" and paramName='"+paramName+"'";
                    List<Map<String, Object>> functionEStructList = commHelp.queryList(functionEStructSql);*/
                    if (functionEStructList != null && functionEStructList.size() > 0) {
                        String[] fieldName = new String[functionEStructList.size() + 1];
                        Map<String, String> isMainKeyMap = new HashMap();//主键集合
                        for (int n = 0; n < functionEStructList.size(); n++) {
                            String paramNameMatch = functionEStructList.get(n).get("paramname") + "";
                            if (paramName.equalsIgnoreCase(paramNameMatch)) {//二级参数名与三级参数名称一致
                                String isMainKey = functionEStructList.get(n).get("ismainkey") + "";
                                if ("1".equals(isMainKey)) {
                                    /*这里用来获取过账接口返回的结构中不存在主键的接口
                                     **返回结构没有主键直接在导出属性结构表中加上对应的主键：格式：导入表名-主键名，如paramFieldName=ITAB-LIFNR
                                     * 当前逻辑适用于传参结构为{"":{}}的类型
                                     */
                                    if (ErpConstant.EXPORT_MAIN_KEY.equals(functionEStructList.get(n).get("paramfieldtype"))) {
                                        String paramfieldname = functionEStructList.get(n).get("paramfieldname") + "";
                                        if (paramfieldname.indexOf("-") != -1) {
                                            String[] paramfieldnames = paramfieldname.split("-");
                                            JSONObject jsonObject = JSONObject.parseObject(paramMap);
                                            JSONArray itab = JSONObject.parseArray("[" + jsonObject.get(paramfieldnames[0]).toString() + "]");
                                            String paramItem = itab.getJSONObject(0).get(paramfieldnames[1]) + "";
                                            exportMainMap.put(paramfieldnames[1], paramItem);
                                        }
                                    }
                                    isMainKeyMap.put(functionEStructList.get(n).get("fieldname") + "", (functionEStructList.get(n).get("mainKeytype")) + "");
                                }
                                fieldName[n] = (String) functionEStructList.get(n).get("fieldname");//初始化字段数组,struct类型数据插入时用这里的字段数组
                            }
                            if ((n + 1) == functionEStructList.size()) {
                                fieldName[n] = "batch";
                            }
                        }
                        Map<String, Object> map = functionEStructList.get(0);
                        String tableName = (String) map.get("tablename");//数据表名
                        String dataBaseName = (String) map.get("databasename");//数据库名
                        String isUseMappingTable = (String) map.get("isusemappingtable");//是否使用映射表
                        if (returnVO != null && StringUtils.isNotBlank(tableName) && "Y".equals(isUseMappingTable)) {//返回结果集不为空，且映射表名不为空才进行映射插入操作
                            String batch = UUID.randomUUID().toString().replaceAll("-", "");//数据同步批次值
                            //struct类型,暂时按只有一条记录处理
                            if (ErpConstant.PARAM_TYPE_STRUCT.equals(paramType)) {
                                Map<String, Object> insertMap = returnVO.getStructMap().get(paramName);
                                if (insertMap != null) {//对应的返回结构对象不为空才执行数据同步
                                    if (insertMap != null && insertMap.size() > 0) {
                                        insertMap.put("batch", batch);
                                    }
                                    Object[] result = commHelp.insertlfdjorder(insertMap, isMainKeyMap, fieldName, tableName, "Y".equals(needCommit) ? "update" : "add", "", dataBaseName);
                                    if (result != null && result[1] != null && StringUtils.isNotBlank((String) result[1])) {
                                        errorSb.append(result[1] + "");
                                        //isexecute=0未处理，isexecute=1已处理
                                        String sqlError = "insert into tb_erp_error_info(id, content, functionid, requestjson, errorinfo, createtime, isexecute, tablename,databasename) VALUES";
                                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                        String values = "('" + uuid + "', '" + errorSb.toString().replaceAll("\'", "\"") + "', '" + functionId + "', '" + paramMap + "', '', '" + SF_DATETIME.format(new Date()) + "', '0', '" + tableName + "','" + dataBaseName + "')";
                                        //commHelp.insert(sqlError+values);
                                        baErpFunctionClient.executeInsertSql(sqlError + values);
                                        errorSb.delete(0, errorSb.length());//清空内容
                                    }
                                }
                            } else if (ErpConstant.PARAM_TYPE_TABLE.equals(paramType)) {//table类型
                                //根据返回的表名获取返回的结果集
                                List<Map<String, Object>> insertMap = returnVO.getTablesMap().get(paramName);
                                List<Object[]> insertObjArr = new ArrayList<Object[]>();
                                Long startTime = System.currentTimeMillis();
                                for (int i = 0; i < insertMap.size(); i++) {
                                    if (i == 0) {
                                        int num = 0;
                                        //将要插入的字段顺序与值的顺序一致
                                        for (String key : insertMap.get(0).keySet()) {
                                            fieldName[num] = key;
                                            num++;
                                        }
                                        if (!insertMap.get(0).containsKey("batch")) {
                                            fieldName[fieldName.length] = "batch";
                                        }
                                    }

                                    Object[] result = null;
                                    if ("Y".equals(needCommit)) {
                                        Map<String, Object> insertObjectMap = insertMap.get(i);
                                        insertObjectMap.put("batch", batch);
                                        insertObjectMap.putAll(exportMainMap);
                                        //一条一条的插入
                                        result = commHelp.insertlfdjorder(insertObjectMap, isMainKeyMap, fieldName, tableName, "Y".equals(needCommit) ? "update" : "add", "", dataBaseName);
                                    } else {//查询接口默认以批量插入方式执行
                                        insertMap.get(i).put("batch", batch);//同步批次值
                                        insertObjArr.add(insertMap.get(i).values().toArray());
                                        //批量插入
                                        if (i % 1000 == 0) {
                                            System.out.println(i);
                                            result = commHelp.batchInsert(insertObjArr, fieldName, tableName, "add", "", dataBaseName);
                                            insertObjArr.clear();
                                            insertObjArr = new ArrayList<Object[]>();
                                        } else if (i == insertMap.size() - 1 && i % 1000 != 0) {
                                            System.out.println(i);
                                            result = commHelp.batchInsert(insertObjArr, fieldName, tableName, "add", "", dataBaseName);
                                            insertObjArr = new ArrayList<Object[]>();
                                        }
                                    }
                                    //将错误信息保存到数据
                                    if (result != null && result[0] != null && StringUtils.isNotBlank((String) result[0])) {
                                        //isexecute=0未处理，isexecute=1已处理
                                        //避免因返回的错误信息中存在单引号导致数据插入失败
                                        errorSb.append(result[0] + "");
                                        String sqlError = "insert into tb_erp_error_info(id, content, functionid, requestjson, errorinfo, createtime, isexecute, tablename,databasename) VALUES";
                                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                        String values = "('" + uuid + "', '" + errorSb.toString().replaceAll("\'", "\"") + "', '" + functionId + "', '" + paramMap + "', '', '" + SF_DATETIME.format(new Date()) + "', '0', '" + tableName + "','" + dataBaseName + "')";
                                        //commHelp.insert(sqlError+values);
                                        baErpFunctionClient.executeInsertSql(sqlError + values);
                                        errorSb.delete(0, errorSb.length());//清空内容
                                    }
                                }
                                Long endTime = System.currentTimeMillis();
                                System.out.println("用时：" + ((endTime - startTime)) + "毫秒");
                                log.info("用时：" + ((endTime - startTime)) + "毫秒");
                            }

                        }
                    }
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    public static void setTablesStructParam(String paramValue, JCoFunction function, boolean flag) {

        //对表结构参数设值
        if (StringUtils.isNotBlank(paramValue) && paramValue.indexOf("__") != -1) {
            String[] tabArr = paramValue.split("@__@");
            for (String tableStr : tabArr) {
                if (tableStr.split("__").length > 1) {
                    String[] tableInfo = tableStr.split("__");
                    JCoTable table = null;
                    JCoStructure structure = null;

                    JSONObject jsonObject = JSONObject.parseObject(tableInfo[1]);
                    if (jsonObject != null) {//flag为false代表表结构为structs
                        if (!flag) {
                            structure = function.getImportParameterList().getStructure(tableInfo[0]);
                        } else {
                            table = function.getTableParameterList().getTable(tableInfo[0]);
                            table.appendRow();
                        }
                        Iterator iterator = jsonObject.keySet().iterator();
                        while (iterator.hasNext()) {
                            String key = (String) iterator.next();
                            if (!flag) {
                                structure.setValue(key, jsonObject.get(key));
                            } else {
                                table.setValue(key, jsonObject.get(key));
                            }
                        }
                    }
                }
            }
        }
    }


    private Object convertToSapType(String type, Object value) throws Exception {
        try {
            if (value == null) {
                return value;
            }
            if (ErpConstant.DATA_TYPE_DATE.equalsIgnoreCase(type)) {
                if (((String) value).split(" ").length > 4) {//如果是Wed Jan 15 00:00:00 CST 2014 格式
                    return SF_SAP_DATE.format(TIME_ZONE.parse((String) value));
                } else if (((String) value).indexOf("-") < 0) {
                    return SF_SAP_DATE.format(new Date((String) value));
                } else {
                    return SF_SAP_DATE.format(SF_DATE.parse((String) value));
                }
            } else if (ErpConstant.DATA_TYPE_TIME.equalsIgnoreCase(type)) {
                if (((String) value).split(" ").length > 4) {//如果是Wed Jan 15 00:00:00 CST 2014 格式
                    return SF_SAP_DATE.format(TIME_ZONE.parse((String) value));
                } else if (((String) value).indexOf("-") < 0) {
                    return SF_SAP_TIME.format(new Date((String) value));
                } else {
                    return SF_SAP_TIME.format(SF_TIME.parse((String) value));
                }
            } else {
                return String.valueOf(value);
                //return IntefaceUtil.convertDateType(value,"STRING");
            }
        } catch (ParseException e) {
            log.error(e.getMessage() + type + "  ");
            System.out.println(type);
            System.out.println(value);
            System.out.println(value.getClass());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 根据functionName从redis中获取配置信息，若redis中不存在则发起查询
     *
     * @param functionName
     * @param baErpFunctionClient
     * @param redisTemplate
     * @return
     */
    public ParamEntity getParamEntity(String functionName, BaErpFunctionClient baErpFunctionClient, RedisTemplate redisTemplate) {
        ParamEntity paramEntity = new ParamEntity();
        Map<String, Object> functionMap = null;
        List<Map<String, Object>> functionInputList = null;
        List<Map<String, Object>> functionIStructList = null;
        List<Map<String, Object>> functionExportList = null;
        List<Map<String, Object>> functionEStructList = null;

//        if(redisTemplate.opsForValue().get(ErpConstant.BA_ERP_FUNCTION+functionId)==null){
        RestResponse restResponse = baErpFunctionClient.queryByFunctionName(functionName);
        if (restResponse.getData() != null) {
            functionMap = (Map<String, Object>) restResponse.getData();
            //redisTemplate.opsForValue().set(ErpConstant.BA_ERP_FUNCTION+functionName,functionMap, 24*60*60, TimeUnit.SECONDS);
        }
//        }else{
//            functionMap = (Map<String, Object>)redisTemplate.opsForValue().get(ErpConstant.BA_ERP_FUNCTION+functionId);
//        }
        String functionId = functionMap.get("id") + "";
//        if(redisTemplate.opsForValue().get(ErpConstant.BA_ERP_FUNCTIONIMPORT+functionId)==null){
        Object inputData = baErpFunctionClient.queryBaErpFunctionImportListByMainId(functionId).getData();
        if (inputData != null) {
            functionInputList = (List<Map<String, Object>>) inputData;
            //redisTemplate.opsForValue().set(ErpConstant.BA_ERP_FUNCTIONIMPORT+functionId,functionInputList, 24*60*60, TimeUnit.SECONDS);
        }
//        }else{
//            functionInputList = (List<Map<String, Object>>)redisTemplate.opsForValue().get(ErpConstant.BA_ERP_FUNCTIONIMPORT+functionId);
//        }

//        if(redisTemplate.opsForValue().get(ErpConstant.BA_ERP_FUNCTIONISTRUCT+functionId)==null){
        Object iStructData = baErpFunctionClient.queryBaErpFunctionIstructListByMainId(functionId).getData();
        if (iStructData != null) {
            functionIStructList = (List<Map<String, Object>>) iStructData;
            //redisTemplate.opsForValue().set(ErpConstant.BA_ERP_FUNCTIONISTRUCT+functionId,functionIStructList, 24*60*60, TimeUnit.SECONDS);
        }
//        }else{
//            functionIStructList = (List<Map<String, Object>>)redisTemplate.opsForValue().get(ErpConstant.BA_ERP_FUNCTIONISTRUCT+functionId);
//        }

//        if(redisTemplate.opsForValue().get(ErpConstant.BA_ERP_FUNCTIONEXPORT+functionId)==null){
        Object exportData = baErpFunctionClient.queryBaErpFunctionExportListByMainId(functionId).getData();
        if (exportData != null) {
            functionExportList = (List<Map<String, Object>>) exportData;
            //redisTemplate.opsForValue().set(ErpConstant.BA_ERP_FUNCTIONEXPORT+functionId,functionExportList, 24*60*60, TimeUnit.SECONDS);
        }
//        }else{
//            functionExportList = (List<Map<String, Object>>)redisTemplate.opsForValue().get(ErpConstant.BA_ERP_FUNCTIONEXPORT+functionId);
//        }

//        if(redisTemplate.opsForValue().get(ErpConstant.BA_ERP_FUNCTIONESTRUCT+functionId)==null){
        Object eStructData = baErpFunctionClient.queryBaErpFunctionEstructListByMainId(functionId).getData();
        if (eStructData != null) {
            functionEStructList = (List<Map<String, Object>>) eStructData;
            //redisTemplate.opsForValue().set(ErpConstant.BA_ERP_FUNCTIONESTRUCT+functionId,functionEStructList, 24*60*60, TimeUnit.SECONDS);
        }
//        }else{
//            functionEStructList = (List<Map<String, Object>>)redisTemplate.opsForValue().get(ErpConstant.BA_ERP_FUNCTIONESTRUCT+functionId);
//        }

        paramEntity.setFunctionMap(functionMap);
        paramEntity.setFunctionImportList(functionInputList);
        paramEntity.setFunctionIStructList(functionIStructList);
        paramEntity.setFunctionExportList(functionExportList);
        paramEntity.setFunctionEStructList(functionEStructList);
        return paramEntity;
    }
}
